<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="950px"
        :clickModalClose="true"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <div class="mb-2 flex items-center text-sm">
        <el-radio-group v-model="radio1" class="ml-4">
          <el-radio label="0" size="large">单笔回款</el-radio>
          <el-radio label="1" size="large">合并回款</el-radio>
        </el-radio-group>
      </div>
      <div v-show="radio1 == '0'" >
        <el-form
            ref="formRef"
            :model="formData"
            label-width="110px"
            :rules="formRules"
            :inline="true"
        >
          <el-form-item label="案件名称" prop="caseName">
            <el-input
                class="w-[300px]"
                v-model="formData.caseName"
                placeholder="请输入案件名称"
            />
          </el-form-item>
          <el-form-item label="回款时间" prop="topUrgent">
            <el-date-picker
                style="width: 300px"
                class="flex-1 !flex"
                v-model="formData.topUrgent"
                type="datetime"
                clearable
                placeholder="请选择回款时间"
            />
          </el-form-item>
          <el-form-item label="回款金额" prop="amountCashed">
            <el-input
                class="w-[300px]"
                v-model="formData.amountCashed"
                placeholder="请输入回款金额"
            />
          </el-form-item>
          <el-form-item label="回款代理日期" prop="collectionAgentDate">
            <el-date-picker
                class="flex-1 !flex"
                style="width: 300px"
                v-model="formData.collectionAgentDate"
                type="datetime"
                clearable
                placeholder="回款代理日期"
            />
          </el-form-item>
          <el-form-item label="回款类型" prop="paymentType">
            <el-select
                class="flex-1 w-[300px]"
                v-model="formData.paymentType"
                placeholder="请选择回款类型"
            >
              <el-option label="正常回款" value="正常回款" />
              <el-option label="退款" value="退款" />
              <el-option label="订金" value="订金" />
            </el-select>
          </el-form-item>

          <el-form-item label="回款代理费" prop="collectingAgencyFees">
            <el-input
                class="w-[300px]"
                v-model="formData.collectingAgencyFees"
                placeholder="请输入回款代理费"
            />
          </el-form-item>
          <el-form-item label="收款公司账户" prop="collectingCompanyAccount">
            <el-select
                class="flex-1 w-[300px]"
                v-model="formData.collectingCompanyAccount"
                placeholder="请选择收款公司账户"
            >
              <el-option label="111" value="111" />
              <el-option label="测试" value="测试" />
            </el-select>
          </el-form-item>
          <el-form-item label="开票时间" prop="timeBilling">
            <el-date-picker
                class="flex-1 !flex"
                v-model="formData.timeBilling"
                style="width: 300px"
                type="datetime"
                clearable
                placeholder="开票时间"
            />
          </el-form-item>
          <el-form-item label="开票金额" prop="invoiceAmount">
            <el-input
                class="w-[300px]"
                v-model="formData.invoiceAmount"
                placeholder="请输入开票金额"
            />
          </el-form-item>
          <el-form-item label="开票币别" prop="paymentMethod">
            <el-select
                class="w-[300px]"
                v-model="formData.paymentCurrency"
                placeholder="请选择货币"
            >
              <el-option label="人民币" value="人民币" />
              <el-option label="美元" value="美元" />
              <el-option label="银行卡" value="银行卡" />
            </el-select>
          </el-form-item>
          <el-form-item label="付款方式" prop="paymentMethod">
            <el-select
                class="w-[300px]"
                v-model="formData.paymentMethod"
                placeholder="请选择付款方式"
            >
              <el-option label="微信" value="微信" />
              <el-option label="支付宝" value="支付宝" />
              <el-option label="银行卡" value="银行卡" />
            </el-select>
          </el-form-item>
          <el-form-item label="发票号码" prop="invoiceNumber">
            <el-input
                class="w-[300px]"
                v-model="formData.invoiceNumber"
                placeholder="请输入发票号码"
            />
          </el-form-item>
          <el-form-item label="合并回款" prop="invoiceNumber">
            <el-input
                class="w-[300px]"
                v-model="formData.consolidatedCollection"
            />
          </el-form-item>
          <el-form-item label="收款人" prop="payee">
            <el-input
                class="w-[300px]"
                v-model="formData.payee"
                placeholder="请输入收款人"
            />
          </el-form-item>
          <el-form-item label="创建人" prop="remarks">
            <el-input
                class="w-[300px]"
                v-model="formData.creator"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
                class="w-[300px]"
                v-model="formData.remarks"
                placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
      </div>
      <div v-show="radio1 == '1'">
        <el-form
            ref="formRef"
            :model="formData"
            label-width="110px"
            :rules="formRules"
            :inline="true"
        >
          <el-form-item label="合同名称" prop="contractName">
            <el-input
                class="w-[300px]"
                v-model="formData.contractName"
                placeholder="请输入合同名称"
            />
          </el-form-item>
          <el-form-item label="回款代理日期" prop="collectionAgentDate">
            <el-date-picker
                class="flex-1 !flex"
                style="width: 300px"
                v-model="formData.collectionAgentDate"
                type="datetime"
                clearable
                placeholder="回款代理日期"
            />
          </el-form-item>
          <el-form-item label="回款代理费" prop="collectingAgencyFees">
            <el-input
                class="w-[300px]"
                v-model="formData.collectingAgencyFees"
                placeholder="请输入回款代理费"
            />
          </el-form-item>
        </el-form>
        <el-table
            class="mt-4"
            size="large"
            v-loading="parentData.loading"
            :data="parentData.lists" stripe
        >
          <el-table-column label="创建人" prop="creator" min-width="100" />
          <el-table-column label="币别" prop="currency" min-width="100" />
          <el-table-column label="回款时间" prop="topUrgent" min-width="100" />
          <el-table-column label="回款金额" prop="amountCashed" min-width="100" />
          <el-table-column label="回款类型" prop="paymentType" min-width="100" />
          <el-table-column label="开票金额" prop="invoiceAmount" min-width="100" />
          <el-table-column label="开票时间" prop="timeBilling" min-width="100" />
          <el-table-column label="付款方式" prop="paymentMethod" min-width="100" />
          <el-table-column label="备注" prop="remarks" min-width="100" />
        </el-table>
      </div>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { answerEdit, answerAdd, answerDetail } from '@/api/answer'
import type Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'

defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  },
  parentData: {
    type: Object,
    default: () => ({})
  }
})
const emit = defineEmits(['success', 'close'])

const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑新建合同回款信息' : '新增新建合同回款明细'
})
const radio1 = ref('0')

const formData = reactive({
  id: '',
  creator: '',
  servicer: '',
  contractId: '1',
  contractName: '',
  customerName: '',
  caseName: '',
  agencyFee: '',
  contractValue: '',
  currency: '',
  paymentCurrency: '',
  officialFee: '',
  currencyid: '',
  paymentCurrencyid: '',
  remarks: '',
  topUrgent: '',
  planTopUrgent: '',
  amountCashed: '',
  paymentType: '',
  collectionAgentDate: '',
  collectingAgencyFees: '',
  collectingCompanyAccount: '',
  invoiceAmount: '',
  timeBilling: '',
  paymentMethod: '',
  consolidatedCollection: '',
  invoiceNumber: '',
  payee: '',
  collectingCompanyAccountid: ''
})

const formRules = {
  topUrgent: [
    {
      required: true,
      message: '请选择回款时间',
      trigger: ['blur']
    }
  ],
  amountCashed: [
    {
      required: true,
      message: '请输入回款金额',
      trigger: ['blur']
    }
  ],
  paymentType: [
    {
      required: true,
      message: '请选择回款类型',
      trigger: ['blur']
    }
  ],
  collectingCompanyAccount: [
    {
      required: true,
      message: '请选择收款公司账户',
      trigger: ['blur']
    }
  ],
  paymentMethod: [
    {
      required: true,
      message: '请选择付款方式',
      trigger: ['blur']
    }
  ],
  contractName: [
    {
      required: true,
      message: '请输入合同名称',
      trigger: ['blur']
    }
  ]
}

// 封装处理日期的函数
const formatDate = (date: string): string | null => {
  if (date) {
    return new Date(date).toISOString().split('T')[0];
  }
  return null;
}

// 在提交数据之前进行处理
const handleSubmit = async () => {
  console.log('123456');
  await formRef.value?.validate();
  const data = { ...formData };
  // 处理所有可能的日期字段
  data.collectionAgentDate = formatDate(data.collectionAgentDate);
  data.timeBilling = formatDate(data.timeBilling);
  data.topUrgent = formatDate(data.topUrgent); // 假设 topUrgent 也需要处理
  console.log(data)
  mode.value === 'edit' ? await answerEdit(data) : await answerAdd(data);
  popupRef.value?.close();
  feedback.msgSuccess('操作成功');
  emit('success');
};

const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
}

const getDetail = async (row: Record<string, any>) => {
  const data = await answerDetail({
    id: row.id
  })
  setFormData(data)
}

const handleClose = () => {
  emit('close')
}

defineExpose({
  open,
  setFormData,
  getDetail
})
</script>